package com.hudongwx.shansun.flashgrament;


import android.graphics.Color;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutCompat;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hudongwx.shansun.R;
import com.hudongwx.shansun.utlis.API;
import com.hudongwx.shansun.utlis.MyJSONobject;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.DbManager;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;


public class GoodkFragment extends Fragment {

    private RelativeLayout rl1, rl2, rl3, rl4, rl5, rl6, rl7, rl8, rl9;
    private ImageView iv1, iv2, iv3, iv4, iv5, iv6, iv7, iv8, iv9, ivtitle, ivcontent;
    private View view;
    private PopupWindow popupWindow;
    private String TAG = "GoodkFragment";
    private View view1;
    private TextView tvTitle;
    private RecyclerView reccyclerView;
    private int nowPage = 1;//需要显示的页码
    private String brandV = "0";//筛选
    private String sortV = "0";//排序
    private MyRewcyAdapter adapter;
    private Handler handler;
    private LinearLayout linearLayout;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        view = inflater.inflate(R.layout.fragment_goodk, container, false);
        initView();
        loadData(null);
        initPopupWindow();
        init();
        handler = new Handler();
        //设置分类中的popuwindow是否可以拉动
        //怎么设置图片的改变
        allClick();
        clickFunBranch();
        linearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               popupWindow.dismiss();
            }
        });
        return view;
    }

    //设置服装的点击事件

    /**
     * 初始化界面
     */
    private void init() {
        adapter = new MyRewcyAdapter();
        //添加布局管理器，创建adapter等
        final GridLayoutManager grid = new GridLayoutManager(getActivity(), 4);
        reccyclerView.setLayoutManager(grid);
        reccyclerView.setAdapter(adapter);
        loadData(null);
        //添加recycler滑动到底部的时间的监听，加载更多
        reccyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (newState == RecyclerView.SCROLL_STATE_IDLE && grid.findLastCompletelyVisibleItemPosition() + 1 == adapter.getItemCount()) {
                  loadData(null);
                }
            }
        });

    }

    //all的全部点击事件
    private void allClick() {
        rl1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (popupWindow == null) {
                    initPopupWindow();

                }
                if (popupWindow.isShowing()) {

                    popupWindow.dismiss();

                } else {
                    popupWindow.showAsDropDown(v, 0, 10);
                    popupWindow.update();

                }
                if (popupWindow.isShowing()) {
                    iv1.setSelected(true);
                } else {
                    iv1.setSelected(false);
                }

                nowPage = 1;

            }

        });
    }

    //将popuwindow中点击事件封装成一个方法
    private void clickFunBranch() {
        //设置ｐｏｐｕｗｉｎｄｏｗ的中内容的点击事件
        rl5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //将运动的图标影藏
                iv1.setSelected(false);
                iv4.setVisibility(View.INVISIBLE);
                iv6.setVisibility(View.INVISIBLE);
                iv7.setVisibility(View.INVISIBLE);
                iv5.setVisibility(View.VISIBLE);
                //将popu消失
                popupWindow.dismiss();
                //将圆数据库数据清空
                adapter.clear();
                //加载数据
                String url = API.fragment_2_web(nowPage, "2", brandV, sortV);
                RequestParams params = new RequestParams(url);

                x.http().get(params, new Callback.CommonCallback<MyJSONobject>() {
                    @Override
                    public void onSuccess(MyJSONobject result) {
                        initLoad(result, "运动");

                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {

                    }

                    @Override
                    public void onCancelled(CancelledException cex) {

                    }

                    @Override
                    public void onFinished() {

                    }
                });


            }
        });
        //设置服装的点击事件
        rl6.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //将运动的图标影藏
                iv4.setVisibility(View.INVISIBLE);
                iv5.setVisibility(View.INVISIBLE);
                iv7.setVisibility(View.INVISIBLE);
                iv6.setVisibility(View.VISIBLE);
                iv1.setSelected(false);
                //将popu消失
                popupWindow.dismiss();
                //将圆数据库数据清空
                adapter.clear();
                //加载数据
                String url = API.fragment_2_web(nowPage, "3", brandV, sortV);
                RequestParams params = new RequestParams(url);
                Log.i(TAG, "onClick: " + params);
                x.http().get(params, new Callback.CommonCallback<MyJSONobject>() {
                    @Override
                    public void onSuccess(MyJSONobject result) {
                        initLoad(result, "服装");

                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {

                    }

                    @Override
                    public void onCancelled(CancelledException cex) {

                    }

                    @Override
                    public void onFinished() {

                    }
                });


            }
        });
        //设置全部的点击的事件

        rl4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                iv5.setVisibility(View.INVISIBLE);
                iv6.setVisibility(View.INVISIBLE);
                iv7.setVisibility(View.INVISIBLE);
                iv4.setVisibility(View.VISIBLE);
                iv1.setSelected(false);
                //将popu消失
                popupWindow.dismiss();
                //将圆数据库数据清空
                adapter.clear();
                //加载数据
                String url = API.fragment_2_web(nowPage, null, brandV, sortV);
                RequestParams params = new RequestParams(url);
                Log.i(TAG, "onClick: " + params);
                x.http().get(params, new Callback.CommonCallback<MyJSONobject>() {
                    @Override
                    public void onSuccess(MyJSONobject result) {
                        initLoad(result, "全部");

                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {

                    }

                    @Override
                    public void onCancelled(CancelledException cex) {

                    }

                    @Override
                    public void onFinished() {

                    }
                });


            }
        });
        rl7.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //将鞋的图标影藏
                iv4.setVisibility(View.INVISIBLE);
                iv6.setVisibility(View.INVISIBLE);
                iv5.setVisibility(View.INVISIBLE);
                iv7.setVisibility(View.VISIBLE);
                iv1.setSelected(false);
                //将popu消失
                popupWindow.dismiss();
                //将圆数据库数据清空
                adapter.clear();
                //加载数据
                String url = API.fragment_2_web(nowPage, "5", brandV, sortV);
                RequestParams params = new RequestParams(url);
                Log.i(TAG, "onClick: " + params);
                x.http().get(params, new Callback.CommonCallback<MyJSONobject>() {
                    @Override
                    public void onSuccess(MyJSONobject result) {
                        initLoad(result, "鞋包");

                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {

                    }

                    @Override
                    public void onCancelled(CancelledException cex) {

                    }

                    @Override
                    public void onFinished() {

                    }
                });


            }
        });
    }

    private void initLoad(MyJSONobject result, String name) {
        Log.i(TAG, "onSuccess: ");
        List<Item> items = new ArrayList<>();
        if (result != null) {
            items = parse2Item(result);
        }

        //将标题设置为运动
        tvTitle.setText(name);
        adapter.addMore(items);
        //判断解析的是否有数剧
        if (items.size() != 0) {
            nowPage++;//当前页码加载成功，把页码+1
            ivtitle.setVisibility(View.VISIBLE);
        } else {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    ivtitle.setVisibility(View.GONE);
                    Toast.makeText(getContext(), "没有数据", Toast.LENGTH_SHORT).show();

                }
            });
        }
    }

    //初始化popuwindown
    private void initPopupWindow() {
        view1 = getActivity().getLayoutInflater().inflate(R.layout.branch_grameng_good_2, null);
        initViewBranch();
        popupWindow = new PopupWindow(view1, LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT);
        //   popupWindow.setBackgroundDrawable(new ColorDrawable());
        //popupWindow.setOutsideTouchable(true);
        //popupWindow.setFocusable(true);


    }

    //初始化控件
    private void initView() {
        rl1 = (RelativeLayout) view.findViewById(R.id.fragment_good_rl_1);
        rl2 = (RelativeLayout) view.findViewById(R.id.fragment_good_rl_2);
        rl3 = (RelativeLayout) view.findViewById(R.id.fragment_good_rl_3);
        iv1 = (ImageView) view.findViewById(R.id.fragment_good_iv_1);
        iv2 = (ImageView) view.findViewById(R.id.fragment_good_iv_2);
        iv3 = (ImageView) view.findViewById(R.id.fragment_good_iv_3);
        ivtitle = (ImageView) view.findViewById(R.id.fragment_good_iv_title);
        tvTitle = (TextView) view.findViewById(R.id.fragment_good_tv_1);
        ivcontent = (ImageView) view.findViewById(R.id.fragment_good_iv_content);
        reccyclerView = (RecyclerView) view.findViewById(R.id.fragment_good_recy_1);
    }

    //初始化popuwindow中的控件
    private void initViewBranch() {
        rl4 = (RelativeLayout) view1.findViewById(R.id.branch_fragment_good_rl_1);
        rl5 = (RelativeLayout) view1.findViewById(R.id.branch_fragment_good_rl_2);
        rl6 = (RelativeLayout) view1.findViewById(R.id.branch_fragment_good_rl_3);
        rl7 = (RelativeLayout) view1.findViewById(R.id.branch_fragment_good_rl_4);
        rl8 = (RelativeLayout) view1.findViewById(R.id.branch_fragment_good_rl_5);
        rl9 = (RelativeLayout) view1.findViewById(R.id.branch_fragment_good_rl_6);
        iv4 = (ImageView) view1.findViewById(R.id.branch_fragment_good_iv_1);
        iv5 = (ImageView) view1.findViewById(R.id.branch_fragment_good_iv_2);
        iv6 = (ImageView) view1.findViewById(R.id.branch_fragment_good_iv_3);
        iv7 = (ImageView) view1.findViewById(R.id.branch_fragment_good_iv_4);
        iv8 = (ImageView) view1.findViewById(R.id.branch_fragment_good_iv_5);
        iv9 = (ImageView) view1.findViewById(R.id.branch_fragment_good_iv_6);
        linearLayout= (LinearLayout) view1.findViewById(R.id.branch_fragment_good_ll);

    }


    class MyRewcyAdapter extends RecyclerView.Adapter {
        private List<Item> dataList = new ArrayList<>();

        private MyRewcyAdapter() {
        }

        public MyRewcyAdapter(List<Item> data) {
            this.dataList.addAll(data);
            notifyDataSetChanged();
        }

        //清空原来的数据
        public void clear() {
            dataList.clear();
            notifyDataSetChanged();
        }

        /**
         * 加载新的一页的时候，加载数据
         *
         * @param tempData
         */
        public void addMore(List<Item> tempData) {
            this.dataList.addAll(tempData);
            notifyItemRangeChanged(this.dataList.size() - tempData.size(), tempData.size());
        }


        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = getActivity().getLayoutInflater().inflate(R.layout.recyview_item, null);
            viewHolder holder = new viewHolder(view);
            return holder;
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            Item item = dataList.get(position);
            viewHolder my = (viewHolder) holder;

            x.image().bind(my.iv10, item.getBrandIcon());

            if ("1".equals(item.isDown)) {
                Drawable drawable = getResources().getDrawable(R.drawable.down);
                drawable.setBounds(0, 0,80, 80);
                //在textview中设置图片
                my.tv.setCompoundDrawables(drawable, null, null, null);
                my.tv.setBackgroundResource(0);
                my.tv.setText("闪降中");
                my.tv.setTextColor(Color.RED);
            } else if (item.getMax() <= item.getLikeNum()) {
                Drawable drawable = getResources().getDrawable(R.drawable.collection_full);
                drawable.setBounds(0, 0,80, 80);
                my.tv.setCompoundDrawables(drawable, null, null, null);
                my.tv.setText("满赞");
                my.tv.setTextColor(Color.RED);
                my.tv.setBackgroundResource(0);
            } else {
                Drawable drawable = getResources().getDrawable(R.drawable.collection_press);
                // 设置图片的大小
                drawable.setBounds(0, 0,80, 80);
                my.tv.setCompoundDrawables(drawable, null, null, null);
                my.tv.setText("点赞");

                my.tv.setTextColor(Color.BLACK);
            }
        }


        @Override
        public int getItemCount() {
            return dataList.size();
        }
    }

    class viewHolder extends RecyclerView.ViewHolder {
        ImageView iv10;
        TextView tv;

        public viewHolder(View itemView) {
            super(itemView);
            iv10 = (ImageView) itemView.findViewById(R.id.recy_item_iv);
            tv = (TextView) itemView.findViewById(R.id.recy_item_tv);
        }
    }

    private void loadData(String type) {
        String url = API.fragment_2_web(nowPage, type, brandV, sortV);
        RequestParams params = new RequestParams(url);

        x.http().get(params, new Callback.CommonCallback<MyJSONobject>() {
            @Override
            public void onSuccess(MyJSONobject result) {
                Log.i(TAG, "onSuccess: ");
                List<Item> items = parse2Item(result);
                try {

                    if (items.size() != 0) {
                        String title = result.getString("title");
                        adapter.addMore(items);
                        x.image().bind(ivtitle, title);
                        nowPage++;//当前页码加载成功，把页码+1
                    } else {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {

                                Toast.makeText(getContext(), "没有数据", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                Log.i(TAG, "onSuccess: " + items.size());


            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });


    }

    public List<Item> parse2Item(JSONObject data) {
        List<Item> list = new ArrayList<>();
        try {
            JSONArray arry = data.getJSONArray("brands");
            if (arry.length() != 0) {
                for (int i = 0; i < arry.length(); i++) {
                    list.add(new Item(arry.getJSONObject(i)));
                }

            }


        } catch (JSONException e) {
            e.printStackTrace();
        }
        return list;
    }

    class Item {
        String brandId;
        String brandName;
        String brandIcon;
        int likeNum;
        int max;
        String isDown;
        String isLike;

        public Item(JSONObject item) throws JSONException {
            brandId = item.getString("brandId");
            brandName = item.getString("brandName");
            brandIcon = item.getString("brandIcon");
            likeNum = item.getInt("likeNum");
            max = item.getInt("max");
            isDown = item.getString("isDown");
            isLike = item.getString("isLike");
        }

        public String getBrandId() {
            return brandId;
        }

        public void setBrandId(String brandId) {
            this.brandId = brandId;
        }

        public String getBrandName() {
            return brandName;
        }

        public void setBrandName(String brandName) {
            this.brandName = brandName;
        }

        public String getBrandIcon() {
            return brandIcon;
        }

        public void setBrandIcon(String brandIcon) {
            this.brandIcon = brandIcon;
        }

        public int getLikeNum() {
            return likeNum;
        }

        public void setLikeNum(int likeNum) {
            this.likeNum = likeNum;
        }

        public int getMax() {
            return max;
        }

        public void setMax(String max) {

        }
    }
}